#pragma once
#include <QFile>
#include <QTextStream>
#include <nlohmann/json.hpp>
#include "rviz_custom_plugins/utils/file_util.h"


using json = nlohmann::json;


namespace rviz_custom_plugins
{

namespace utils
{

template<typename T>
T readFromFile(const QString& filePath) {

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        T defaultValue;
        return defaultValue;
    }
    QTextStream in(&file);
    QString content = in.readAll();
    file.close();

    json j = json::parse(content.toStdString());
    // 要求定义 from_json(const json&, T&)
    return j.get<T>(); 
}


template<typename T>
void writeToFile(const QString& filePath, const T& obj)
{
    // 要求定义 to_json(json&, const T&)
    json j = obj; 
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        throw std::runtime_error(("Cannot open file: " + filePath).toStdString());
    }

    QTextStream out(&file);
    out << QString::fromStdString(j.dump(4));
    file.close();
}



}


}